package org.example.fastproject.web.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.fastproject.core.bean.PageParam;
import org.example.fastproject.core.bean.SysUserDetails;
import org.example.fastproject.core.enums.DeletedEnum;
import org.example.fastproject.core.exception.Asserts;
import org.example.fastproject.core.utils.SecurityUtil;
import org.example.fastproject.web.sys.model.SysRole;
import org.example.fastproject.web.sys.mapper.SysRoleMapper;
import org.example.fastproject.web.sys.model.SysRolePermission;
import org.example.fastproject.web.sys.model.SysUserRole;
import org.example.fastproject.web.sys.model.dto.role.RoleInsertDto;
import org.example.fastproject.web.sys.model.dto.role.RolePermissionDto;
import org.example.fastproject.web.sys.model.dto.role.RoleUpdateDto;
import org.example.fastproject.web.sys.model.vo.role.RoleVo;
import org.example.fastproject.web.sys.service.SysCacheService;
import org.example.fastproject.web.sys.service.SysRolePermissionService;
import org.example.fastproject.web.sys.service.SysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.fastproject.web.sys.service.SysUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author 王海舟
 * @since 2023-01-16 11:54:01
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Resource
    private SysRolePermissionService rolePermissionService;

    @Resource
    private SysUserRoleService userRoleService;

    @Resource
    private SysCacheService cacheService;

    @Override
    @Transactional
    public boolean save(RoleInsertDto dto) {
        String name = dto.getName();
        SysRole sysRole = this.getOne(Wrappers.<SysRole>lambdaQuery()
                .eq(SysRole::getName,name)
                .ne(SysRole::getDeleted,DeletedEnum.TRUE.getData()));
        if(Objects.nonNull(sysRole))
            Asserts.fail("角色名已存在");
        SysUserDetails user = SecurityUtil.getUser();
        sysRole = BeanUtil.toBean(dto,SysRole.class);
        sysRole.setName(name);
        sysRole.setDescription(dto.getDescription());
        sysRole.setCreateUser(user.getId());
        sysRole.setCreateTime(user.getDate());
        sysRole.setUpdateUser(user.getId());
        sysRole.setUpdateTime(user.getDate());
        return this.save(sysRole);
    }

    @Override
    @Transactional
    public boolean remove(Long id) {
        //获取拥有此角色的用户id集合
        List<Long> userIds = userRoleService.list(Wrappers.<SysUserRole>lambdaQuery()
                        .eq(SysUserRole::getRoleId, id))
                .stream()
                .map(sysUserRole -> {
                    return sysUserRole.getUserId();
                }).collect(Collectors.toList());
        //删除用户与角色关联
        userRoleService.remove(Wrappers.<SysUserRole>lambdaQuery()
                .eq(SysUserRole::getRoleId,id));
        //删除角色
        boolean success = this.update(Wrappers.<SysRole>lambdaUpdate()
                .set(SysRole::getDeleted, DeletedEnum.TRUE.getData())
                .eq(SysRole::getId, id));
        if(success){
            //删除相关缓存
            if(CollectionUtil.isNotEmpty(userIds)){
                for(Long userId : userIds){
                    cacheService.removePermission(userId);
                }
            }
        }
        return success;
    }

    @Override
    @Transactional
    public boolean update(RoleUpdateDto dto) {
        String name = dto.getName();
        SysRole sysRole = this.getOne(Wrappers.<SysRole>lambdaQuery()
                .eq(SysRole::getName,name)
                .ne(SysRole::getDeleted,DeletedEnum.TRUE.getData())
                .ne(SysRole::getId,dto.getId()));
        if(Objects.nonNull(sysRole))
            Asserts.fail("角色名已存在");
        SysUserDetails user = SecurityUtil.getUser();
        sysRole = BeanUtil.toBean(dto,SysRole.class);
        sysRole.setId(dto.getId());
        sysRole.setDescription(dto.getDescription());
        sysRole.setUpdateUser(user.getId());
        sysRole.setUpdateTime(user.getDate());
        boolean success = this.updateById(sysRole);
        if(success){
            //获取拥有此角色的用户id集合
            List<Long> userIds = userRoleService.list(Wrappers.<SysUserRole>lambdaQuery()
                            .eq(SysUserRole::getRoleId, dto.getId()))
                    .stream()
                    .map(sysUserRole -> {
                        return sysUserRole.getUserId();
                    }).collect(Collectors.toList());
            //删除相关缓存
            if(CollectionUtil.isNotEmpty(userIds)){
                for(Long userId : userIds){
                    cacheService.removePermission(userId);
                }
            }
        }
        return success;
    }

    @Override
    @Transactional
    public boolean permission(RolePermissionDto dto) {
        //删除已分配权限
        rolePermissionService.remove(Wrappers.<SysRolePermission>lambdaQuery()
                .eq(SysRolePermission::getRoleId,dto.getRoleId()));
        //获取拥有此角色的用户id集合
        List<Long> userIds = userRoleService.list(Wrappers.<SysUserRole>lambdaQuery()
                        .eq(SysUserRole::getRoleId, dto.getRoleId()))
                .stream()
                .map(sysUserRole -> {
                    return sysUserRole.getUserId();
                }).collect(Collectors.toList());
        //删除相关缓存
        if(CollectionUtil.isNotEmpty(userIds)){
            for(Long userId : userIds){
                cacheService.removePermission(userId);
            }
        }
        //重新分配权限
        List<SysRolePermission> list = dto.getPermissionIds().stream().map(permissionId -> {
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setRoleId(dto.getRoleId());
            sysRolePermission.setPermissionId(permissionId);
            return sysRolePermission;
        }).collect(Collectors.toList());
        return rolePermissionService.saveBatch(list);
    }

    @Override
    public Page<RoleVo> page(PageParam param) {
        Page page = new Page(param.getNum(),param.getSize());
        this.page(page);
        List<SysRole> list =page.getRecords();
        List<RoleVo> roles = list.stream().map(sysRole -> {
            return BeanUtil.toBean(sysRole,RoleVo.class);
        }).collect(Collectors.toList());
        page.setRecords(roles);
        return page;
    }
}
